﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Collections;

namespace HexunMicrobloggingClientUI
{
    public partial class SelectRSSSourceForm : Form
    {
        public SelectRSSSourceForm()
        {
            InitializeComponent();

            // Initialize header of two listview.
            InitListViewsHeader();

            // Initialize list view items
            isInitListviewItemSuccess = ReadRssToListView();

            // Enable buttons.
            btnSelect.Enabled = btnSelectAll.Enabled = isInitListviewItemSuccess;
        }

        private bool isInitListviewItemSuccess = false;

        private bool ReadRssToListView()
        {
            Dictionary<string, string> rssList;
            string errorMessage, filePath = System.Windows.Forms.Application.StartupPath + "\\" + DefaultRssFile;
            
            bool readResult = ReadRssFile(filePath, out rssList, out errorMessage);
            if (readResult)
            {
                foreach (KeyValuePair<string, string> kvp in rssList)
                {
                    ListViewItem listItem = new ListViewItem(kvp.Key);
                    listItem.SubItems.Add(kvp.Value);
                    this.lvAllRss.Items.Add(listItem);
                }
            }

            return readResult;
        }

        private bool ReadRssFile(string filePath, out Dictionary<string, string> dicRssInfo, out string errorMessage)
        {
            dicRssInfo = new Dictionary<string, string>();
            errorMessage = string.Empty;

            try
            {
                using (StreamReader streamReader = new StreamReader(filePath, System.Text.Encoding.GetEncoding("gb2312")))
                {
                    string strLine = null;
                    while ((strLine = streamReader.ReadLine()) != null)
                    {
                        strLine = strLine.Trim();
                        if (!string.IsNullOrEmpty(strLine) &&
                            !string.IsNullOrWhiteSpace(strLine) &&
                            !strLine.StartsWith("#"))
                        {
                            string[] strKey_Value = strLine.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                            if (strKey_Value.Length < 2 || strKey_Value[1].StartsWith("#"))
                            {
                                continue;
                            }

                            string keyTitle = strKey_Value[0];
                            string valueRssUri = strKey_Value[1];
                            string tryValue = string.Empty;
                            if (!dicRssInfo.TryGetValue(keyTitle, out tryValue))
                            {
                                dicRssInfo.Add(keyTitle, valueRssUri);
                            }
                        }
                    }
                    streamReader.Close();
                }
                return true;
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
                return false;
            }
        }

        public string DefaultRssFile
        {
            get
            {
                return "RSSList.txt";
            }
        }

        public string SelectdRssUris
        {
            get
            {
                string selectedRssUris = string.Empty;
                foreach (ListViewItem item in this.lvSelectedRss.Items)
                {
                    selectedRssUris += item.SubItems[1].Text + ";";
                }
                return selectedRssUris;
            }
        }

        #region Initialization of controls

        /// <summary>
        /// Initialize the header of list view controls.
        /// </summary>
        private void InitListViewsHeader()
        {
            ColumnHeader columnHeader0 = new ColumnHeader();
            columnHeader0.Text = "Title";
            columnHeader0.TextAlign = HorizontalAlignment.Left;
            columnHeader0.Width = 60;

            ColumnHeader columnHeader1 = new ColumnHeader();
            columnHeader1.Text = "RSS Source";
            columnHeader1.TextAlign = HorizontalAlignment.Center;
            columnHeader1.Width = 200;

            lvAllRss.Columns.Add(columnHeader0);
            lvAllRss.Columns.Add(columnHeader1);


            ColumnHeader columnHeader2 = new ColumnHeader();
            columnHeader2.Text = "Title";
            columnHeader2.TextAlign = HorizontalAlignment.Left;
            columnHeader2.Width = 60;

            ColumnHeader columnHeader3 = new ColumnHeader();
            columnHeader3.Text = "RSS Source";
            columnHeader3.TextAlign = HorizontalAlignment.Center;
            columnHeader3.Width = 200;

            lvSelectedRss.Columns.Add(columnHeader2);
            lvSelectedRss.Columns.Add(columnHeader3);

            /*
            string[] foodList = new string[]{
                "Juice", 
                "Coffee", 
                "Cereal & Milk", 
                "Fruit Plate", 
                "Toast & Jelly", 
                "Bagel & Cream Cheese"};
            string[] foodPrice = new string[]{
                "1.09", 
                "1.09", 
                "2.19", 
                "2.49", 
                "1.49", 
                "1.49"};

            for (int count = 0; count < foodList.Length; count++)
            {
                ListViewItem listItem = new ListViewItem(foodList[count]);

                listItem.SubItems.Add(foodPrice[count]);
                listItem.SubItems.Add(foodPrice[count]);

                lvBatchIssue.Items.Add(listItem);
            }
            */
        }

        #endregion

        #region Event handler of controls

        private void SelectRSSSourceForm_Load(object sender, EventArgs e)
        {
            // Read RssSource
        }

        private void lvAllRss_DoubleClick(object sender, EventArgs e)
        {
            Dictionary<string, string> dicRightSelectedItems = new Dictionary<string, string>();
            foreach (ListViewItem item in this.lvSelectedRss.Items)
            {
                dicRightSelectedItems.Add(item.SubItems[0].Text, item.SubItems[1].Text);
            }

            ListViewItem clickedItem = ((ListView)sender).SelectedItems[0];
            string keyTitle = clickedItem.SubItems[0].Text;
            string valueRssUri = clickedItem.SubItems[1].Text;

            string tryValueRssUri = string.Empty;
            if (!dicRightSelectedItems.TryGetValue(keyTitle, out tryValueRssUri))
            {
                ListViewItem listItem = new ListViewItem(keyTitle);
                listItem.SubItems.Add(valueRssUri);
                this.lvSelectedRss.Items.Add(listItem);
            }

            // Update 'OK' button.
            btnOK.Enabled = lvSelectedRss.Items.Count > 0;
        }

        private void lvSelectedRss_DoubleClick(object sender, EventArgs e)
        {
            lvSelectedRss.Items.Remove(lvSelectedRss.SelectedItems[0]);

            btnRemove.Enabled = btnRemoveAll.Enabled = lvSelectedRss.Items.Count > 0;

            // Update 'OK' button.
            btnOK.Enabled = lvSelectedRss.Items.Count > 0;
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            Dictionary<string, string> dicRightSelectedItems = new Dictionary<string, string>();
            foreach (ListViewItem item in this.lvSelectedRss.Items)
            {
                dicRightSelectedItems.Add(item.SubItems[0].Text, item.SubItems[1].Text);
            }

            Dictionary<string, string> dicLeftSelectedItems = new Dictionary<string, string>();
            foreach (ListViewItem item in this.lvAllRss.SelectedItems)
            {
                string keyTitle = item.SubItems[0].Text;
                string valueRssUri = item.SubItems[1].Text;

                string tryValueRssUri = string.Empty;
                if (!dicRightSelectedItems.TryGetValue(keyTitle, out tryValueRssUri))
                {
                    ListViewItem listItem = new ListViewItem(keyTitle);
                    listItem.SubItems.Add(valueRssUri);
                    this.lvSelectedRss.Items.Add(listItem);
                }
            }

            // Update 'OK' button.
            btnOK.Enabled = lvSelectedRss.Items.Count > 0;

            /*
            SortedList<int, RssInfo> slRightSelectedItems = new SortedList<int, RssInfo>();
            */

            /*
            Dictionary<int, RssInfo> dicRightSelectedItems = new Dictionary<int, RssInfo>();
            foreach (ListViewItem item in this.lvSelectedRss.SelectedItems)
            {
                dicRightSelectedItems.Add(item.Index, new RssInfo(item.SubItems[0].Text, item.SubItems[1].Text));
            }
            // Sort the dictionary.
            var result = from pair in dicRightSelectedItems orderby pair.Key select pair;
            var orderedValues = dicRightSelectedItems.OrderBy(kv => kv.Key).Select(kv => kv.Value);
            */
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in this.lvSelectedRss.SelectedItems)
            {
                lvSelectedRss.Items.Remove(item);
            }

            // Update 'OK' button.
            btnOK.Enabled = lvSelectedRss.Items.Count > 0;
        }

        private void btnSelectAll_Click(object sender, EventArgs e)
        {
            lvSelectedRss.Items.Clear();

            foreach (ListViewItem item in this.lvAllRss.Items)
            {
                ListViewItem listItem = new ListViewItem(item.SubItems[0].Text);
                listItem.SubItems.Add(item.SubItems[1].Text);
                this.lvSelectedRss.Items.Add(listItem);
            }

            // Update 'OK' button.
            btnOK.Enabled = lvSelectedRss.Items.Count > 0;
        }

        private void btnRemoveAll_Click(object sender, EventArgs e)
        {
            lvSelectedRss.Items.Clear();

            // Update 'OK' button.
            btnOK.Enabled = lvSelectedRss.Items.Count > 0;
        }

        private void lvAllRss_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Update 'OK' button.
            btnOK.Enabled = lvSelectedRss.Items.Count > 0;

            ListView listView = (ListView)sender;
            
            // Update 'Select All' button's 'Enabled' status.
            btnSelectAll.Enabled = listView.Items.Count > 0;

            ListView.SelectedListViewItemCollection selectedItems = listView.SelectedItems;
            if (selectedItems == null && selectedItems.Count == 0)
            {
                return;
            }

            // Update 'Select' button's 'Enabled' status.
            btnSelect.Enabled = selectedItems.Count >= 1;
        }

        private void lvSelectedRss_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Update 'OK' button.
            btnOK.Enabled = lvSelectedRss.Items.Count > 0;

            ListView listView = (ListView)sender;

            // Update 'Select All' button's 'Enabled' status.
            btnRemoveAll.Enabled = listView.Items.Count > 0;

            ListView.SelectedListViewItemCollection selectedItems = listView.SelectedItems;
            if (selectedItems == null && selectedItems.Count == 0)
            {
                return;
            }

            // Update 'Select' button's 'Enabled' status.
            btnRemove.Enabled = selectedItems.Count >= 1;
        }

        #endregion

        private void btnOK_Click(object sender, EventArgs e)
        {

        }
    }
}